<?php

namespace app\socketio\controller;

use Workerman\Worker;
use Workerman\Lib\Timer;
use think\Controller;
use think\Db;
use app\common\AudioFileAllOperation;
use app\common\cache\RedisPackage;
use app\api\model\LiveSpeech1;

//服务端

class Index extends Controller
{
    protected static $redis;

    public function index()
    {
        $worker = new Worker();

        $worker->onWorkerStart = function () {
            Timer::add(5, function(){
                $this->UsbUploadFileHandler();
            });
        };
        // 运行worker
        Worker::runAll();
    }

    //锁
    public function UploadFileEntry($db)
    {
        // $fp = fopen(__DIR__ . "/keys/" . md5('Upload_file'), 'w+');
        // if (!flock($fp, LOCK_EX | LOCK_NB)) {
        //     return;
        // }
        $this->UsbUploadFileHandler();
        // flock($fp, LOCK_UN);
        // fclose($fp);
    }

    public function UsbUploadFileHandler(){
        while(($file_attr = $this->FilePopFromList())){
            $this->transferTragger($file_attr);
            //添加到队列中
            $off_arr = [
                'id' => $file_attr['id'],
                'file' => pathinfo($file_attr['des_path'])['filename'] . '.wav',
            ];
            self::$redis->offTransPush($off_arr);
        }
    }
    
    
    public function FilePopFromList(){
        self::$redis=RedisPackage::getInstance();
        $data = self::$redis->uploadFilePop();
        return json_decode($data, true);
    }

    public function transferTragger($file_attr)
    {
        try {

            $file = LiveSpeech1::get($file_attr['id']);

            //测试用
            //@file_put_contents("/disc1/asr/WebAdmin/data/time/" . $file->formatname . ".txt", "startTransCode is   -------" . time() . "\r\n", FILE_APPEND);
            // switch($file_attr['type']){
            //     case 1:
            //         $dir = config('share_path') . config('huisheng.upload_audio_dir') . DS . $file->formatname;
            //         $result = $this->handler($dir . DS . $file->formatname . "." . pathinfo($file->filename)['extension'], $file->uid);
            //     break;
            //     case 2:
            //         $result = $this->handler($file_attr['ori_path'], $file->uid);
            //     break;
            //     default: break;
            // }
            $result = $this->handler($file_attr['ori_path'], $file_attr['des_path'],$file->uid);
            //更新状态
            //$file->transition_state = 1;
            $file->update_time = time();
            $file->start_time = time();
            $file->seconds = $result['seconds'];
            $file->size = filesize($result['out_path']);
            $file->save();
            Db::name('meeting_speech')->where('meeting_id', $file->id)->update(['lvsr_status' => 2]);
            return resultArray(['data' => '']);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            $file->transition_state = 3;
            $file->update_time = time();
            $file->save();
            return resultArray(['error' => $e->getMessage()]);
        }
    }

    private function handler($in_path, $out_path,$uid)
    {
        //$out_path = config('share_path') . config('huisheng.box_audio_dir') . DS . $out_name . ".wav";
        AudioFileAllOperation::moveFileandTrans2Wav($in_path, $out_path);
        $seconds = AudioFileAllOperation::waveDetailLength($out_path);
        if (!is_dir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $uid)) {
            mkdir(config('share_path') . config('huisheng.upload_mp3_path') . DS . $uid, 0777, true);
        }
        $mp3_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $uid . DS . pathinfo($out_path)['filename'] . ".mp3";
        AudioFileAllOperation::wavTrans2Another($out_path, $mp3_path);
        $json_path = config('share_path') . config('huisheng.upload_mp3_path') . DS . $uid . DS . pathinfo($out_path)['filename'] . ".json";
        AudioFileAllOperation::wave2json($out_path, $json_path, $seconds);
        return ['out_path' => $out_path, 'seconds' => $seconds];
    }
}
